<template>
<div class="dictManage tree-page">
  <search-block>
    <template slot="button">
      <el-button type="primary" @click="doFilter">查询</el-button>
      <el-button type="primary" @click="addDict(null)">添加字典</el-button>
    </template>
    <el-form inline :model="search" label-width="100px" @submit.native.prevent>
      <el-form-item label="字典名:">
        <el-input v-model="search.dictName" clearable></el-input>
      </el-form-item>
    </el-form>
  </search-block>
  <div class="dict-tree-block tree-block tree-page-block">
    <el-tree
      :key="treeKey"
      ref="tree"
      :data="dictData"
      accordion
      node-key="code"
      :filter-node-method="filterNode"
      :props="{ label: 'dictName', children: 'children' }"
      lazy
      :load="loadChild">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span class="tree-node-label">{{ node.label }}</span>
        <span class="tree-node-btn">
          <el-link
            :underline="false"
            type="primary"
            @click="() => addDict(data)">
            添加字典项
          </el-link>
          <el-link
            :underline="false"
            type="primary"
            @click="() => editDict(data)">
            编辑
          </el-link>
          <el-popconfirm
            title="是否确认删除该字典项？"
            @confirm="delDict(data)">
            <el-link
              disabled
              slot="reference"
              :underline="false"
              type="danger">
              删除
            </el-link>
          </el-popconfirm>
        </span>
      </span>
    </el-tree>
  </div>
  <y-form
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    destroy-on-close
    width="50%"
    :form-attrs="forms.formAttrs"
    :columns="getFormColumns()"
    @ensure="ensureModel">
  </y-form>
</div>
</template>

<script>
export default {
  name: "dictManage",
  data(){
    return{
      treeKey: 0,
      filterTag: false,
      search:{
        dictName: ''
      },
      dictData:[],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加字典',
          'EDIT': '编辑字典'
        },
        formModel:{
          dictPid: '',
          pcode: '',
          code: '',
          dictName: '',
          orderNum: '',
          remarks: ''
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            code: [
              {required: true, message: "请输入字典编码", trigger: "blur"},
              {
                validator: (rule, value, callback) => {
                  if(this.forms.formsType === 'EDIT'){
                    callback();
                  }else{
                    this.$$validateCode(
                      this.$api.system.uniqueDict,
                      { code: value }, callback);
                  }
                },
                trigger: 'blur'
              }
            ],
            dictName: [{required: true, message: "请输入字典名称", trigger: "blur"}],
          }
        }
      },
    }
  },
  methods:{
    refresh(){
      this.treeKey++;
      this.filterTag = true;
    },
    doFilter(){
      this.$refs.tree.filter(this.search.dictName);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.dictName.indexOf(value) >= 0 || data.code.indexOf(value) >= 0;
    },
    getFormColumns(){
      return [
        {
          label: "父级字典编码",
          prop: "pcode",
          comp:{
            compType: 'input',
            attrs:{
              disabled: true
            }
          }
        },
        {
          label: "字典编码",
          prop: "code",
          comp:{
            compType: 'input',
            attrs:{
              clearable: true,
              disabled: this.forms.formsType === 'EDIT',
              maxlength: 60,
              showWordLimit: true
            }
          }
        },
        {
          label: "字典名称",
          prop: "dictName",
          comp:{
            compType: 'input',
            attrs:{
              clearable: true,
              maxlength: 30,
              showWordLimit: true
            }
          }
        },
        {
          label: "排序",
          prop: "orderNum",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true
            }
          }
        },
        {
          label: "备注",
          prop: "remarks",
          comp:{
            compType: 'input',
            attrs:{
              type: 'textarea',
              maxlength: '100',
              showWordLimit: true
            }
          }
        }
      ]
    },
    resetForm(defForm){
      let form = defForm || this.forms.currentForm;
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = (form && form[key]) ? form[key] : '';
      })
    },
    ensureModel(form){
      let newForm;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = Object.assign({}, form);
      }
      this.$yAxios({
        url: this.$api.system.saveDict,
        data: newForm,
        loading: true
      }, info => {
        this.$bus.$emit('refreshDict', newForm.pCode || newForm.code)
        newForm = info;
        switch(this.forms.formsType){
          case 'ADD':{
            if(this.forms.currentForm){//添加字典项
              if(!this.forms.currentForm.children){
                this.$set(this.forms.currentForm, 'children', []);
              }
              this.$refs['tree'].getNode(this.forms.currentForm).expanded = true;
              this.$refs['tree'].append(newForm, this.forms.currentForm);
            }else{//添加字典
              this.refresh();
            }
            break;
          }
          case 'EDIT':{
            Object.assign(this.forms.currentForm, newForm);
            break;
          }
        }
        this.$message({
          type: 'success',
          message: '保存成功'
        });
      })
    },
    loadChild(node,resolve){
      if(node.level === 0){
        this.$yAxios({
          url: this.$api.system.queryRootDict,
          data:{
            name: ''
          },
          loading: true
        },info => {
          if(this.filterTag){
            this.filterTag = false;
            this.$nextTick(() => {
              this.doFilter();
            })
          }
          resolve(info)
        }, () => {
          resolve([])
        })
      }else{
        this.$yAxios({
          url: this.$api.system.queryDict,
          data:{
            pcode: node.data.code
          }
        },info => {
          resolve(info)
        }, () => {
          resolve([])
        })
      }
    },
    addDict(data){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = data;
      this.resetForm(data ? ({
        pcode: data.code,
        dictPid: data.id
      }) : null);
      this.forms.showForm = true;
    },
    editDict(data){
      this.forms.formsType = 'EDIT';
      this.forms.currentForm = data;
      this.resetForm();
      this.forms.showForm = true;
    },
    delDict(data){
      if(data.children && data.children.length){
        this.$alert('无法删除包含子节点的字典或字典项', {
          confirmButtonText: '确定'
        });
        return;
      }
      this.$yAxios({
        url: this.$api.system.removeDict,
        data:{
          id: data.id
        },
        loading: true,
      }, info => {
        this.$bus.$emit('refreshDict', data.pCode || data.code)
        this.$refs['tree'].remove(data);
        this.$message({
          type: 'success',
          message: '删除成功'
        });
      })
    }
  }
}
</script>

<style scoped lang="less">
</style>
